package com.chuangjiangx.member.stored.ddd.domain.subscribe;

import com.chuangjiangx.commons.JacksonUtils;
import com.chuangjiangx.member.basic.ddd.domain.service.MemberRedisDomainService;
import com.chuangjiangx.member.stored.ddd.domain.service.MbrRefundService;
import com.chuangjiangx.member.stored.ddd.domain.event.MbrRefundSuccessEvent;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;

import java.io.Serializable;

/**
 * @author cj-ch
 * @date 2018/5/23 下午3:54
 * 会员退款成功后事件监听
 */
@Slf4j
public class MbrRefundSuccessListener {

    @Autowired
    protected ObjectMapper objectMapper;

    @Autowired
    protected MemberRedisDomainService memberRedisDomainService;

    @Autowired
    protected MbrRefundService mbrRefundService;



    public void handleMessage(Serializable message){
        if(null == message || StringUtils.isBlank(message.toString())){
            return;
        }

        MbrRefundSuccessEvent event = convertMessage(message);

        if(!check(event)){
            return;
        }

        mbrRefundService.refund(event);
    }

    protected MbrRefundSuccessEvent convertMessage(Serializable message) {
        return JacksonUtils.toObject(objectMapper,message.toString(),MbrRefundSuccessEvent.class);
    }

    /**
     * 前置条件检查
     * @param event
     * @return
     */
    protected boolean check(MbrRefundSuccessEvent event){
        if(null == event){
            return false;
        }
        if(!memberRedisDomainService.merchantOpenedMember(event.getMerchantId())){
            //过滤未开通会员功能的商户
            return false;
        }
        return true;
    }


}
